const fs = require("fs");
const xlsx = require("node-xlsx");
const mongoose = require("mongoose")

const Schema =mongoose.Schema
const documentSchema = new Schema({
    title: String,
    material: [String],
    qualifications: [String],
    date: { type: String, required: true },
    clickNum: { type: Number, required: true }
});
const doc = mongoose.model("document", documentSchema);
mongoose.connect('mongodb://116.62.133.67:27017/test');


function readDirRecur(folder,callback) {
    fs.readdir(folder,function(err,files){
        let count = 0;
        let checkEnd = function(){
            ++count == files.length&&callback();
        }
        files.forEach(file =>{
            let fullPath = folder + '/'+file;
            fs.stat(fullPath,(err,stats) =>{
                if(stats.isDirectory()){
                    return readDirRecur(fullPath,checkEnd);
                }else{
                    if(file[0]=='.'){

                    }else{
                        if(!file.match(".xmind")) {
                            fileList.push(fullPath);
                        }
                    }
                    checkEnd();
                }
            })
        })
        files.length === 0&& callback();
    })
}
function getRandomInt(max) {
    return Math.floor(Math.random() * max);
}
function readXls(fileName) {
    let sheets = xlsx.parse(fileName);
    let material = []
    let quality = []
    sheets.forEach(sheet =>{
        for (let rowId in sheet['data']){
            let row = sheet['data'][rowId];
            if(typeof(row[0])=='number'&& row.length>=3){
                let str  = `${row[0]}.`;
                for (let i =1;i<row.length;i++){
                    str = str.concat(row[i])
                }
                material.push(str);
            }else if(row.length==1){
                quality.push(row[0]);
            }else{

            }
        }
    })
    let name = fileName.split("/")
    let clickNum = getRandomInt(100)+1;
    let date = new Date();
    let dateString= `${date.getFullYear().toString()}-${((date.getMonth()+clickNum)%12+1).toString()}-${((date.getDate()+clickNum)%28+1).toString()}`
    let sheetname = name[name.length-2]+name[name.length-1]
    doc.create({title: sheetname,material: material, qualifications: quality,date: dateString,clickNum: clickNum},(err)=>{
        if(err){
            console.log("err")
        }
        console.log(sheetname);
    })
}
const fileList = [];
const timeStart = new Date();
const filePath = "D:\\RS_XMindParser-master\\广州市人社政务服务事项清单";
readDirRecur(filePath,file=>{
    console.log('done',new Date()-timeStart);
    console.log(fileList);
    for(let i =0;i<fileList.length;i++) {
        readXls(fileList[i]);
    }
})


